package club.baimahu.pencil.servlet;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class HttpServletResponse {

    private ChannelHandlerContext ctx;
    private HttpRequest httpRequest;
    private String charset = "utf-8";

    public HttpServletResponse(ChannelHandlerContext ctx, HttpRequest httpRequest){
        this.ctx = ctx;
        this.httpRequest = httpRequest;
    }

    public ChannelHandlerContext getChannelHandlerContext(){
        return this.ctx;
    }


    public void write(Object out){
        try{
            FullHttpResponse response = null;
            String msg = "<html><head><title>test</title></head><body>你请求uri为：</body></html>";

            String json = JSONObject.toJSONString(out);


            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(out == null ?"".getBytes(Charset.forName(charset)):
//                    out.toString().getBytes(charset)));
                    json.getBytes(charset)));

            response.headers().set("Content-Type","application/json; charset=utf-8");
//            response.headers().set("Content-Type","text/html; charset=utf-8");
            ctx.write(response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            ctx.flush();
            ctx.close();
        }
    }

    
}
